package com.yhd.task.dynamic;

import com.yhd.task.model.TaskVO;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import javax.annotation.Resource;
import java.util.Random;

/**
 * 动态生成定时任务
 *
 * @author yinhuidong3@xiaomi.com
 * @since 2021/7/3
 */
@Component
public class DynamicCreateTask {

    @Resource
    private SpringContainerExtend springContainerExtend;

    @Resource
    private CreateClass createClass;

    public TaskVO createTask(TaskVO taskVO){
        //if className isEmpty create it and beanName cause: the bean is never created
        if (StringUtils.isEmpty(taskVO.getClassName())){
            //TODO 控制生成的bean名字
            String className = String.valueOf((char) (new Random().nextInt(26) + 65));
            taskVO.setClassName(className);
            String beanName = lowerFirstChar(className);
            taskVO.setBeanName(beanName);
        }
        Class<?> clazz = createClass.compile(taskVO);
        springContainerExtend.registerBean(taskVO.getBeanName(),clazz);
        //System.out.println(springContainerExtend.getBean(taskVO.getBeanName()));
        return taskVO;
    }

    private String lowerFirstChar(String str){
        char [] chars = str.toCharArray();
        chars[0] += 32;
        return String.valueOf(chars);
    }

}
